package com.hx.base.servlet.velocity;

import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.VelocityStrutsUtil;
import org.apache.struts2.views.util.ContextUtil;
import org.apache.struts2.views.velocity.StrutsVelocityContext;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.context.ChainedContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class VelocityFixedManager extends VelocityManager {
	private static final Logger LOG = LoggerFactory.getLogger(VelocityFixedManager.class);
	private static final String IS_BACKPAGE = "is_backpage";
	@SuppressWarnings("unchecked")
	@Override
	public Context createContext(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
		Context result = null;
		VelocityContext[] chainedContexts = prepareChainedContexts(req, res,stack.getContext());
		StrutsVelocityContext context = new StrutsVelocityContext(chainedContexts, stack);
		Map standardMap = ContextUtil.getStandardContext(stack, req, res);
		for (Iterator iterator = standardMap.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			context.put((String) entry.getKey(), entry.getValue());
		}

		 //action调用之前将页面中的is_backpge值放入request中
		 String backValue = (String)req.getAttribute(IS_BACKPAGE);
		 if ( backValue != null){
			  stack.setValue(IS_BACKPAGE, backValue);
		 }
		 LOG.debug("===request===" + "is_backpage==>:stack value[" + stack.findValue(IS_BACKPAGE) + "] == request attribute["+backValue + "]======");
		 
		 context.put(STRUTS, new VelocityStrutsUtil(getVelocityEngine(),context, stack, req, res));

		ServletContext ctx = null;
		try {
			ctx = ServletActionContext.getServletContext();
		} catch (NullPointerException npe) {
			 // in case this was used outside the lifecycle of struts servlet
            LOG.debug("internal toolbox context ignored");
		}

		 if (toolboxManager != null && ctx != null) {
	            ChainedContext chained = new ChainedContext(context, getVelocityEngine(), req, res, ctx);
	            chained.setToolbox(toolboxManager.getToolbox(chained));
	            result = chained;
	        } else {
	            result = context;
	        }

	        req.setAttribute(KEY_VELOCITY_STRUTS_CONTEXT, result);
	        return result;
		
	}
}